<?php

namespace App\Model\Dao;

use App\Model\Enum\RiskRuleMchRefTypeEnum;
use App\Utils\CustomUtils;
use App\Concern\BaseDao;
use App\Utils\DateUtils;
use Hyperf\Database\Query\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\Arr;
use Redis;
use App\Utils\RedisUtils;
use Hyperf\Utils\Codec\Json;

/**
 * RiskRuleMchRefDao
 */
class RiskRuleMchRefDao extends BaseDao {

    /**
     * 表名常量
     * 联表的时候通过XxxDao::TABLE获取
     */
    const TABLE = "risk_rule_mch_ref";

    // 不支持软删除
    protected $softDelete = null;

    /**
     * 父类中通过静态函数获取表名, 因为不能通过静态常量获取, 这个函数是固定写在子类中的
     */
    public static function table (): string {
        return self::TABLE;
    }

    const KEY_MCH_WHITE = 'table:'.self::TABLE.':white:mch';

    const STATUS = [
        0 => '禁用',
        1 => '正常'
    ];    

    const TYPE = [
        1 => '风控集合',
        2 => '可疑风控集合',
        3 => '白名单集合'
    ];


    public function getStatusList () {
        return $this::STATUS;
    }

    public function strStatus ($key, $default = '') {
        return Arr::get($this->getStatusList(), $key, $default);
    }    

    public function getTypeList () {
        return $this::TYPE;
    }

    public function strType ($key, $default = '') {
        return Arr::get($this->getTypeList(), $key, $default);
    }

    /**
     * 排序
     *
     * @param Builder $builder
     * @param array   $params
     *
     * @return Builder|mixed
     */
    protected function _buildOrder (Builder $builder, $params = []) {

        // 通过前端提交的参数排序
        if (Arr::exists($params, "orderBy")) {

            [$prop, $order] = $params["orderBy"];

            if (in_array($order, ["asc", "desc"])) {

                //switch ($prop) {
                //    case "yieldMonth":
                //        $builder->orderBy("main.yieldMonth", $order);
                //        break;
                //    default:
                //        break;
                //}
            }
        }
        else {
            $builder->orderBy('main.mchNo');
            $builder->orderBy('main.type', 'asc');
        }

        // 如果友其他固定的排序需求, 在这里写, 例如按照时间降序
        // $builder->orderBy("main.createTime", "desc");

        // 追加父类的排序, 父类按照ID升序, 保证排序结果唯一
        return parent::_buildOrder($builder, $params);
    }

    /**
     * 查询条件
     *
     * @param $params
     *
     * @return Builder
     */
    protected function _buildQueryString ($params) {

        // 本表一律命名为main
        $main = sprintf("%s AS main", self::TABLE);

        // 联表表明获取
        $mch             = sprintf('%s AS mch', MchInfoDao::TABLE);
        $collection      = sprintf('%s AS collection', RiskRuleCollectionDao::TABLE);
        $collectionWhite = sprintf('%s AS collectionWhite', RiskRuleWhitetextDao::TABLE);

        $builder = DB::table($main);
        $builder->join($mch, 'mch.mchNo', 'main.mchNo');
        $builder->leftJoin($collection, 'collection.id', 'main.collectionId');
        $builder->leftJoin($collectionWhite, 'collectionWhite.id', 'main.collectionId');

        // 通过 Arr::exists 来判断是否存在该键, isset不准确
        Arr::exists($params, 'mchNo') && $builder->where('main.mchNo', $params['mchNo']);
        Arr::exists($params, 'type') && $builder->where('main.type', $params['type']);
        Arr::exists($params, 'mchIdList') && $builder->whereIn('mch.id', $params['mchIdList']);

        $builder->selectRaw(join(',', [
            'main.mchNo',
            'main.collectionId',
            'main.type',
            'main.status',
            'main.createBy',
            'main.createTime',

            'mch.id AS mchId',
            'mch.mchName',

            'IF(ISNULL(collection.id), collectionWhite.whiteTextName, collection.collectionName) AS collectionName',
            'IF(ISNULL(collection.id), collectionWhite.status, collection.status) AS collectionStatus',
        ]));

        return $builder;
    }

    /**
     * 获取商户关联白名单规则列表
     *
     * @param string $mchNo 商户号
     */
    public function readMchWhiteRuleList ($mchNo) {

        // 读取缓存
        $key  = self::KEY_MCH_WHITE.":{$mchNo}";
        $list = RedisUtils::redisResource()->get($key);

        if (!!$list) {
            $list = unserialize($list);
        }
        else {
            // 读取数据
            $main  = sprintf("%s AS main", self::TABLE);
            $white = sprintf("%s AS white", RiskRuleWhitetextDao::TABLE);
            $conn  = sprintf("%s AS conn", RiskRuleWhitetextConnDao::TABLE);
            $rule  = sprintf("%s AS rule", RiskRuleWhitetextParamDao::TABLE);

            $builder = DB::table($main);

            $builder->join($white, "white.id", "main.collectionId");
            $builder->join($conn, "conn.whiteTextId", "white.id");
            $builder->join($rule, "rule.id", "conn.paramId");

            $builder->where([
                "main.mchNo"   => $mchNo,
                "main.type"    => RiskRuleMchRefTypeEnum::WHITE,
                "main.status"  => 1,
                "white.status" => 1,
                "conn.status"  => 1,
                "rule.status"  => 1,
            ]);

            $builder->selectRaw(join(",", [
                "main.mchNo",
                "main.collectionId",
                "white.whiteTextName AS collectionName",
                "rule.*",
            ]));

            $list = $builder->get()->toArray();

            // 写入缓存
            RedisUtils::redisResource()->set($key, serialize($list), DateUtils::getDayRemainSecond());
        }

        return $list;
    }

    /**
     * 删除缓存:商户关联白名单规则列表
     *
     * @param $mchNo
     */
    public function clearMchWhiteRuleList ($mchNo) {
        $key = self::KEY_MCH_WHITE.":{$mchNo}";
        RedisUtils::redisResource()->del($key);
    }


}
